import {Col, message, Row} from "antd";
import  React from "react";
import {getApp, update, versionCompare} from "../../common/utils";
import {LoadingOutlined} from "@ant-design/icons";
import {Divider} from "antd";

const {useMemo, useState} = React;
export default function StatusBar() {
    const currentVersion = getApp().getVersion();
    const [updating, setUpdating] = useState(false);
    const [version, setVersion] = useState(currentVersion);
    return useMemo(() => {
        function doUpdate() {
            setUpdating(true);
            update()
                .then(res => {
                    if (!res?.version) {
                        message.error("检查更新失败")
                        return;
                    }
                    const r = versionCompare(currentVersion, res.version);
                    if (!r) {
                        message.success("当前使用的版本为最新版本")
                    } else if (r > 0) {
                        message.success("当前版本是超前版本");
                    } else {
                        message.success(`最新版本为${res.version}`);
                    }
                })
                .catch(err => {
                    message.error(`检查更新失败： ${err}`)
                })
                .finally(() => setUpdating(false));
        }

        return (
            <Row className="status-bar">
                <Col flex={1}>
                    双击应用，修改自动保存
                </Col>
                <Col>
                    v{getApp().getVersion()}
                    <Divider type="vertical"/>
                    {updating ? <a><LoadingOutlined/> 正在检查更新</a> : <a onClick={doUpdate}>检查更新</a>}
                </Col>
            </Row>
        );
    }, [updating]);
}